package com.kun.sync.step;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.concurrent.ExecutorService;

import com.kun.sync.processor.ConvertProcessor;
import com.kun.sync.reader.ReaderInterface;
import com.kun.sync.util.DatabaseConnection;
import com.kun.sync.writer.BatchWriter;

/**
 * 步骤 factory
 * 
 * @author zjkorder (2018/1/30 10:26)
 */
public class StepFactory {

	public static void start(ReaderInterface reader, ConvertProcessor processor, BatchWriter batchWriter)
			throws SQLException {
		ResultSet resultSet = reader.next();
		while (resultSet != null) {
			test(resultSet, processor, batchWriter);
			resultSet = reader.next();
		}
		reader.close();
		batchWriter.close();
	}

	public static void start(ReaderInterface reader, ConvertProcessor processor, BatchWriter batchWriter,
			ExecutorService executorService) throws SQLException {
		ResultSet resultSet = reader.next();
		while (resultSet != null) {
			final ResultSet taskResultSet = resultSet;
			executorService.execute(() -> {
				try {
					test(taskResultSet, processor, batchWriter);
				} catch (SQLException e) {
					e.printStackTrace();
				}
			});
			resultSet = reader.next();
		}
		executorService.shutdown();
		while (!executorService.isTerminated()) {

		}
		reader.close();
		batchWriter.close();
	}

	private static void test(ResultSet resultSet, ConvertProcessor processor, BatchWriter writer) throws SQLException {
		while (resultSet.next()) {
			ConvertProcessor.ParamsType paramsType = processor.convert(resultSet);
			if (paramsType.getParams() != null) {
				if (paramsType.getSqlType() != null) {
					writer.addBatch(paramsType.getParams(), paramsType.getSqlType());
				} else {
					writer.addBatch(paramsType.getParams());
				}
			}
		}
		DatabaseConnection.close(null, null, resultSet);

	}
}
